﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;

using System.Collections;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace Inference
{
    public partial class frmFact : Form
    {
        public frmFact(SqlConnection _conn, int _factID, string _factString, int _slotID, int _frameID, bool _if_conc, bool _ifEdit)
        {
            FactID = _factID;
            SlotID = _slotID;
            FrameID = _frameID;
            FactString = _factString;
            conn = _conn;
            IfConc = _if_conc;
            IfEdit = _ifEdit;

            InitializeComponent();
        }

        int FactID = -1, SlotID = -1, FrameID = -1, SlotDomTypeForPicker = -1;
        string FactString = "";
        SqlConnection conn;
        Frames.SlotForm fmsl;
        DataTable datat_frame;
        TaleEntities Tale = new TaleEntities();
        Frame frame = null;
        Slot slot = null;
        bool IfConc = false, IfEdit=false;

        public int Place = -1, CompSlotID = -1, DomType = -1, ValueID = -1;


        private void LoadPlace()
        {
            //datat_frame = new DataTable();
            //cmb_place.Items.Clear();
            //try
            //{
            //    datat_frame = fmsl.LoadSlotsFromDB(conn, FrameID);
            //}
            //catch { }
            //if (datat_frame != null)
            //{
            //    for (int i = 0; i < datat_frame.Rows.Count; i++)
            //    {
            //        cmb_place.Items.Add(datat_frame.Rows[i].ItemArray[1].ToString());
            //    }
            //}
        }

        private void SelectNeccessary()
        {

            //if (FactString != "")
            //{
            //    string[] parts = FactString.Split('=');
            //    if (parts[0].EndsWith("!"))
            //        parts[0] = parts[0].Remove(parts[0].Length - 1).Trim();
            //    parts[1] = parts[1].Trim();
            //    string[] nest_slots = parts[0].Split('.');
            //    if (cmb_place.Items.Count >= 0)
            //        cmb_place.SelectedIndex = cmb_place.Items.IndexOf(nest_slots[0].Trim());
            //    if (comboBox2.Items.Count >= 0)
            //        comboBox2.SelectedIndex = comboBox2.Items.IndexOf(nest_slots[1].Trim());
            //    if (comboBox3.Items.Count >= 0)
            //        comboBox3.SelectedIndex = comboBox3.Items.IndexOf(nest_slots[2].Trim());
            //    if (cmb_value.Items.Count >= 0)
            //        cmb_value.SelectedIndex = cmb_value.Items.IndexOf(parts[1]);
            //}
            var prod_fact = Tale.ViewProductions.Where(v=>v.ID == FactID);
            if (prod_fact.Count() > 0)
            {
                var prod = prod_fact.First();
                if (ucSlots.SelectedSlotID == -1)
                    ucSlots.SelectedSlotID = (int)prod.CompSlotID;
                if (cmb_value.Items.Count > 0)
                {
                    try
                    {

                        var value = Tale.DValues.Where(v => v.ID == prod.ValueID).First();
                        cmb_value.SelectedIndex = cmb_value.Items.IndexOf(value.Value.ToString());
                    }
                    catch
                    {
                        cmb_value.SelectedIndex = -1;
                    }

                }
            }
        }



        private void frmFact_Load(object sender, EventArgs e)
        {
            fmsl = (Frames.SlotForm)Application.OpenForms["SlotForm"];
            int success = 0;            
            try
            {
                frame = Tale.Frame.Where(v => v.ID == FrameID).First();
                slot = Tale.Slot.Where(v => v.ID == SlotID).First();
                success = 0;
            }
            catch { success = -1; }
            if (success == 0)
            {             
             //   {
                ucSlots.IfConc = IfConc;
                    ucSlots.InitSlotPicker(frame, slot.Number);
              //  }
            }
            if (IfConc)
                chb_neg.Enabled = false;
            SelectNeccessary();
            if (IfEdit)
                this.Text = "Редактирование факта";
            else
                this.Text = "Добавление факта";
            //LoadPlace();
            //if (FactID != -1)
            //    SelectNeccessary();
        }
        private DataTable GetSubfrFromSlotVal(int valID)
        {
            var def_val = Tale.DValues.Where(v => v.ID == valID);
            if (def_val != null)
            {
                Inference.DValues df = def_val.First();
                var subfr_ind = Tale.Frame.Where(v => v.Name.ToLower() == df.Value.ToLower());
                if (subfr_ind != null)
                    return fmsl.LoadSlotsFromDB(conn, subfr_ind.FirstOrDefault().ID);
            }
            return null;
        }

        private void cmb_place_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (cmb_place.SelectedIndex >= 0)
            //{
            //    int dom_id = (int)datat_frame.Rows[cmb_place.SelectedIndex].ItemArray[2];
            //    if (dom_id == 1 || dom_id == 7) // subfr
            //    {
            //        comboBox2.Enabled = true;
            //        comboBox2.SelectedIndex = -1;
            //        comboBox2.Items.Clear();
            //        // load слоты субфрейма
            //        DataTable subfr_slots = GetSubfrFromSlotVal((int)datat_frame.Rows[cmb_place.SelectedIndex].ItemArray[3]);
            //        for (int i = 0; i < subfr_slots.Rows.Count; i++)
            //        {
            //            comboBox2.Items.Add(subfr_slots.Rows[i].ItemArray[1].ToString());
            //        }
            //    }
            //    else
            //    {
            //        comboBox2.SelectedIndex = -1;
            //        comboBox3.SelectedIndex = -1;
            //        comboBox2.Enabled = false;
            //        comboBox3.Enabled = false;
            //        var vals_ids = Tale.DomainsValues.Where(v => v.DomID == dom_id);    
            //        comboBox2.Items.Clear();
            //        foreach (Inference.DomainsValues dv in vals_ids)
            //        {
            //            var val_id = Tale.DValues.Where(v => v.ID == dv.ID);
            //            if (val_id!=null)
            //                comboBox3.Items.Add(val_id.FirstOrDefault().Value);
            //        }
            //    }
            //}
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //// can be slot or frame
            //if (comboBox2.SelectedIndex != -1)
            //{
            //     int dom_id = (int)datat_frame.Rows[cmb_place.SelectedIndex].ItemArray[2];
            //     if (dom_id == 1 || dom_id == 7) // frame
            //     {
            //         string df = comboBox2.Text;
            //         var subfr_ind = Tale.Frame.Where(v => v.Name.ToLower() == df.ToLower());  // frame
            //         if (subfr_ind != null && subfr_ind.Count()>0)
            //         {
            //             DataTable datat = new DataTable();
            //             datat = fmsl.LoadSlotsFromDB(conn, subfr_ind.FirstOrDefault().ID);
            //             if (datat != null)
            //             {
            //                 comboBox3.Items.Clear();
            //                 comboBox3.SelectedIndex = -1;
            //                 comboBox3.Enabled = true;
            //                 for (int i = 0; i < datat.Rows.Count; i++)
            //                 {
            //                     comboBox3.Items.Add(datat.Rows[i].ItemArray[1]);
            //                     cmb_value.Items.Add(datat.Rows[i].ItemArray[1]);
            //                 }
            //             }
            //         }
            //     }
            //     else
            //     {
            //         var vals_ids = Tale.DomainsValues.Where(v => v.DomID == dom_id);
            //         foreach (Inference.DomainsValues dv in vals_ids)
            //         {
            //             var val_id = Tale.DValues.Where(v => v.ID == dv.ID);
            //             if (val_id != null)
            //                 comboBox3.Items.Add(val_id.FirstOrDefault().Value);
            //         }
            //     }
            //}
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }


        private void ucSlots_Picked()
        {
            if (ucSlots.SelectedSlotID >= 0)
            {
                //int place = ucSlots.Place;
                //if (place!=-1)
                {
                    textBox1.Text = "";
                    //List<Slot> lst = CheckIf.GetProductionChain(place,ucSlots.SelectedSlotID);
                    //foreach (Slot sl in lst)
                    //{
                    //    textBox1.Text += "'" + sl.Name + "'.";
                    // }

                    textBox1.Text = ucSlots.PathStringCut;//textBox1.Text.Substring(0, textBox1.Text.Length - 1);
                    if (textBox1.Text != "")
                    {
                        LoadDomainValues();
                        SelectNeccessary();
                    }
                }
               
            }
        }

        private void LoadDomainValues()
        {
            cmb_value.Items.Clear();
            Slot slot = Tale.Slot.Where(v=>v.ID == ucSlots.SelectedSlotID).First(); 
            if (slot != null)
            {
                if (ucSlots.SelectedSlotID >= 0)
                {
                    if (slot.DomainType == null || slot.DomainType == 0)
                        SlotDomTypeForPicker = 0;
                    else if (slot.DomainType != null && slot.DomainType > 0)
                        SlotDomTypeForPicker = 1;
                    if (SlotDomTypeForPicker == 0)
                    {
                        var dvals = from dv in Tale.DomainsValues where dv.DomID == slot.Domain orderby dv.Number select dv;
                        //Tale.DomainsValues.Where(v => v.DomID == slot.Domain).OrderBy(v => v.Number);
                        foreach (Inference.DomainsValues dv in dvals)
                        {
                            var value = Tale.DValues.Where(v => v.ID == dv.Value).First();
                            cmb_value.Items.Add(value.Value);
                        }
                    }
                    else if (SlotDomTypeForPicker == 1) // фрейм
                    {
                        List<Frame> frame_values = CheckIf.GetFrameDomain((int)slot.DomainType, Tale);
                        foreach (Frame fr in frame_values)
                        {
                            cmb_value.Items.Add(fr.Name);
                        }
                    }
                    if (cmb_value.Items.Count > 0)
                        cmb_value.SelectedIndex = 0;
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
        }

        public int DomainID = -1;
        public string ValueV = "", Text = "";
        public bool Negation = false;
        // make  public int Place = -1, CompSlotID = -1, DomType = -1, ValueID = -1;
        private void button1_Click(object sender, EventArgs e)
        {
            if (cmb_value.Text != "" && textBox1.Text != "")
            {
                Place = ucSlots.Place;
                CompSlotID = ucSlots.SelectedSlotID;
                Slot slot = Tale.Slot.Where(v => v.ID == ucSlots.SelectedSlotID).First();
                try
                {
                    DomType = (int)slot.DomainType;
                }
                catch { DomType = 0; }
                DomainID = (int)slot.Domain;
                ValueV = cmb_value.Text;
                Text = textBox1.Text;
                Negation = chb_neg.Checked;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

    }
}
